package cn.lili.modules.utils;

import cn.lili.common.exception.BaseServiceException;
import cn.lili.modules.service.AppReadService;
import cn.wildfirechat.pojos.MessagePayload;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.MessageAdmin;
import com.alibaba.fastjson.JSONObject;
import com.api.UserPhpApi;
import com.pojos.OpenAppUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author:xiangqian
 * @date: 2024/3/12 17:39
 */
@Component
@Slf4j
public class MessagePayloadUtils {

    @Resource
    private UserPhpApi userPhpApi;
    @Resource
    private AppReadService appReadService;

    /**
     * 发送消息到野火
     *
     * @param type   类型
     * @param extra  扩展字段，根据实际需要增加
     * @param toUser 发给谁
     */
    public void sendMessagePayload(Integer type, String extra, String toUser) {
        log.info("入参:type--{}extra---{}toUser--{}", type, extra, toUser);
        OpenAppUser userinfoByOpenId = userPhpApi.getUserinfoByOpenId(toUser);

        MessagePayload payload = new MessagePayload();
        payload.setType(3002);
        payload.setPersistFlag(ProtoConstants.PersistFlag.Not_Persist);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", type);
        jsonObject.put("extra", extra);
        payload.setContent(jsonObject.toJSONString());
        try {
            MessageAdmin.multicastMessage("22", new ArrayList<>() {{
                add(userinfoByOpenId.getUId());
            }}, 0, payload);

            //插入阅读记录
            appReadService.updateAppRead(toUser, type, -1);
        } catch (Exception e) {
            throw new BaseServiceException("发送消息失败type=" + type + "extra=" + extra + "toUser" + toUser);
        }
    }
}
